package controllers

import dao.{AnnoDao, DataDao}
import implicits.Implicits._
import play.api.libs.json.{JsNull, Json}
import play.api.mvc.{AbstractController, ControllerComponents}
import tool.{FormTool, Tool}
import utils.Utils

import java.io.File
import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import upickle.default._

/**
 * Created by yz on 10/12/2021
 */
class AnnoController @Inject()(cc: ControllerComponents)(
  implicit val dataDao: DataDao,
  implicit val annoDao: AnnoDao,
) extends AbstractController(cc) {

  def toIndex = Action { implicit request =>
    Ok(views.html.anno.index())
  }

  def getJson = Action { implicit request =>
    val data = FormTool.rsNumberForm.bindFromRequest().get
    val rsNumber = data.rsNumber
    val file = new File(Tool.rsDir, s"${rsNumber}/${rsNumber}.json")
    val json = if (file.exists()) {
      Json.parse(file.str)
    } else JsNull
    Ok(json)
  }

  def getAll = Action.async { implicit request =>
    annoDao.selectAll.map { x =>
      val array = Utils.getArrayByTs(x)
      Ok(Json.toJson(array))
    }
  }

  def all = Action.async { implicit request =>
    annoDao.selectAll.map { x =>
      val array = x.map(x => writeJs(x))
      Ok(writeJs(x))
    }
  }

  def getSelect2Values = Action.async { implicit request =>
    val data = FormTool.keysForm.bindFromRequest().get
    annoDao.selectUniqueValues(data.keys).map { valuess =>
      val vMap = data.keys.zip(valuess).toSeqMap
      Ok(Json.toJson(vMap))
    }
  }


}
